package com.example.wenhua.controller;

import com.example.wenhua.common.Result;
import com.example.wenhua.dto.LoginRequest;
import com.example.wenhua.entity.User;
import com.example.wenhua.service.UserService;
import com.example.wenhua.utils.JwtUtil;
import com.example.wenhua.utils.RoleUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.loginWithToken(loginRequest.getHm(), loginRequest.getPwd());
            if (token != null) {
                User user = userService.getUserByHm(loginRequest.getHm());
                user.setPwd(null); // 清除密码信息
                
                // 创建用户信息Map，包含角色名称
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("hm", user.getHm());
                userInfo.put("role", RoleUtil.getRoleName(user.getRole()));
                userInfo.put("roleValue", user.getRole());
                
                Map<String, Object> result = new HashMap<>();
                result.put("user", userInfo);
                result.put("token", token);
                return Result.success("登录成功", result);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有用户
     */
    @GetMapping
    public Result<List<User>> getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            // 清除密码信息
            users.forEach(user -> user.setPwd(null));
            return Result.success(users);
        } catch (Exception e) {
            return Result.error("查询用户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据用户名查询用户
     */
    @GetMapping("/{hm}")
    public Result<User> getUserByHm(@PathVariable String hm) {
        try {
            User user = userService.getUserByHm(hm);
            if (user != null) {
                user.setPwd(null); // 清除密码信息
                return Result.success(user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("查询用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据角色查询用户
     */
    @GetMapping("/role/{role}")
    public Result<List<User>> getUsersByRole(@PathVariable Integer role) {
        try {
            List<User> users = userService.getUsersByRole(role);
            // 清除密码信息
            users.forEach(user -> user.setPwd(null));
            return Result.success(users);
        } catch (Exception e) {
            return Result.error("查询用户失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增用户
     */
    @PostMapping
    public Result<Void> addUser(@RequestBody User user) {
        try {
            boolean success = userService.addUser(user);
            if (success) {
                return Result.success("用户添加成功", null);
            } else {
                return Result.error("用户添加失败");
            }
        } catch (Exception e) {
            return Result.error("用户添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{hm}")
    public Result<Void> updateUser(@PathVariable String hm, @RequestBody User user) {
        try {
            user.setHm(hm);
            boolean success = userService.updateUser(user);
            if (success) {
                return Result.success("用户信息更新成功", null);
            } else {
                return Result.error("用户信息更新失败");
            }
        } catch (Exception e) {
            return Result.error("用户信息更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{hm}")
    public Result<Void> deleteUser(@PathVariable String hm) {
        try {
            boolean success = userService.deleteUser(hm);
            if (success) {
                return Result.success("用户删除成功", null);
            } else {
                return Result.error("用户删除失败");
            }
        } catch (Exception e) {
            return Result.error("用户删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改密码
     */
    @PutMapping("/{hm}/password")
    public Result<Void> changePassword(@PathVariable String hm, @RequestBody Map<String, String> passwordData) {
        try {
            String oldPwd = passwordData.get("oldPwd");
            String newPwd = passwordData.get("newPwd");
            
            boolean success = userService.changePassword(hm, oldPwd, newPwd);
            if (success) {
                return Result.success("密码修改成功", null);
            } else {
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            return Result.error("密码修改失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置密码（管理员功能）
     */
    @PutMapping("/{hm}/reset-password")
    public Result<Void> resetPassword(@PathVariable String hm, @RequestBody Map<String, String> passwordData) {
        try {
            String newPwd = passwordData.get("newPwd");
            
            boolean success = userService.resetPassword(hm, newPwd);
            if (success) {
                return Result.success("密码重置成功", null);
            } else {
                return Result.error("密码重置失败");
            }
        } catch (Exception e) {
            return Result.error("密码重置失败：" + e.getMessage());
        }
    }
    
    /**
     * 刷新JWT token
     */
    @PostMapping("/refresh-token")
    public Result<Map<String, Object>> refreshToken(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                String newToken = userService.refreshToken(token);
                if (newToken != null) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("token", newToken);
                    return Result.success("Token刷新成功", result);
                } else {
                    return Result.error("Token刷新失败");
                }
            } else {
                return Result.error("无效的token格式");
            }
        } catch (Exception e) {
            return Result.error("Token刷新失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public Result<Map<String, Object>> getCurrentUser(HttpServletRequest request) {
        try {
            String username = (String) request.getAttribute("username");
            if (username != null) {
                User user = userService.getUserByHm(username);
                if (user != null) {
                    // 创建用户信息Map，包含角色名称
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("hm", user.getHm());
                    userInfo.put("role", RoleUtil.getRoleName(user.getRole()));
                    userInfo.put("roleValue", user.getRole());
                    
                    return Result.success(userInfo);
                } else {
                    return Result.error("用户不存在");
                }
            } else {
                return Result.error("未获取到用户信息");
            }
        } catch (Exception e) {
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 验证用户权限
     */
    @GetMapping("/check-permission/{requiredRole}")
    public Result<Map<String, Object>> checkPermission(@PathVariable Integer requiredRole, HttpServletRequest request) {
        try {
            String username = (String) request.getAttribute("username");
            if (username != null) {
                boolean hasPermission = userService.hasPermission(username, requiredRole);
                Map<String, Object> result = new HashMap<>();
                result.put("hasPermission", hasPermission);
                return Result.success(result);
            } else {
                return Result.error("未获取到用户信息");
            }
        } catch (Exception e) {
            return Result.error("权限验证失败：" + e.getMessage());
        }
    }
}